<template>
    <view class="face-verify-container">
      <view class="page-header">
        <text class="page-title">实名认证</text>
        <text class="page-desc">请填写真实信息完成身份认证</text>
      </view>
      
      <view class="form-card">
        <view class="form-header">
          <text class="form-title">主要登记人信息</text>
        </view>
        <uni-forms ref="form" :model="formData" :rules="rules" label-position="top">
          <uni-forms-item label="姓名" name="name" required>
            <uni-easyinput v-model="formData.name" placeholder="请输入姓名" :clearable="true" />
          </uni-forms-item>
          
          <uni-forms-item label="联系方式" name="contacts" required>
            <uni-easyinput v-model="formData.contacts" placeholder="请输入联系方式" :clearable="true" />
          </uni-forms-item>

          <uni-forms-item label="身份证号" name="idCardNumber" required>
            <uni-easyinput v-model="formData.idCardNumber" placeholder="请输入身份证号" :clearable="true" />
          </uni-forms-item>

          <uni-forms-item label="房客类型" name="renterType" required>
            <uni-data-select
              v-model="formData.renterType"
              :localdata="renterTypeOptions"
              placeholder="请选择房客类型"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="选择房间" name="roomId">
            <view class="room-select-wrapper">
              <view class="room-select-container" @click="openRoomSelector">
                <text v-if="selectedRoom" class="selected-room">{{ selectedRoom.name }} - {{ selectedRoom.buildingName }}</text>
                <text v-else class="room-placeholder">点击选择房间</text>
                <uni-icons type="right" size="16" color="#999"></uni-icons>
              </view>
            </view>
          </uni-forms-item>
          
          <uni-forms-item label="人脸照片" name="picUrl" required>
            <view class="face-photo-wrapper">
              <view class="face-photo-container" @click="openPhotoActionSheet('main')">
                <image v-if="formData.picUrl" :src="formData.picUrl" mode="aspectFill" class="face-photo" />
                <view v-else class="face-photo-placeholder">
                  <uni-icons type="camera-filled" size="36" color="#3c9cff"></uni-icons>
                  <text class="placeholder-text">点击上传人脸照片</text>
                </view>
              </view>
              <text class="photo-tip">请上传清晰的正面照片，大小不超过1M</text>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
      
      <!-- 同住人列表 -->
      <view v-for="(tenant, index) in coTenants" :key="index" class="form-card">
        <view class="form-header">
          <text class="form-title">同住人{{index + 1}}信息</text>
          <text class="delete-btn" @click="removeCoTenant(index)">删除</text>
        </view>
        <uni-forms :model="tenant" label-position="top">
          <uni-forms-item label="姓名" name="name">
            <uni-easyinput v-model="tenant.name" placeholder="请输入姓名" :clearable="true" />
          </uni-forms-item>
          
          <uni-forms-item label="联系方式" name="contacts">
            <uni-easyinput v-model="tenant.contacts" placeholder="请输入联系方式" :clearable="true" />
          </uni-forms-item>

          <uni-forms-item label="身份证号" name="idCardNumber">
            <uni-easyinput v-model="tenant.idCardNumber" placeholder="请输入身份证号" :clearable="true" />
          </uni-forms-item>

          <uni-forms-item label="房客类型" name="renterType">
            <uni-data-select
              v-model="tenant.renterType"
              :localdata="renterTypeOptions"
              placeholder="请选择房客类型"
            ></uni-data-select>
          </uni-forms-item>
          
          <uni-forms-item label="人脸照片" name="picUrl">
            <view class="face-photo-wrapper">
              <view class="face-photo-container" @click="openPhotoActionSheet(index)">
                <image v-if="tenant.picUrl" :src="tenant.picUrl" mode="aspectFill" class="face-photo" />
                <view v-else class="face-photo-placeholder">
                  <uni-icons type="camera-filled" size="36" color="#3c9cff"></uni-icons>
                  <text class="placeholder-text">点击上传人脸照片</text>
                </view>
              </view>
              <text class="photo-tip">请上传清晰的正面照片，大小不超过1M</text>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>

      <!-- 添加同住人按钮 -->
      <view class="add-tenant-btn" @click="addCoTenant">
        <uni-icons type="plus" size="20" color="#3c9cff"></uni-icons>
        <text>添加同住人</text>
      </view>

      <view class="submit-btn-container">
        <button type="primary" @click="submitForm" class="submit-btn">提交认证</button>
      </view>
      
      <!-- 底部操作表 -->
      <uni-popup ref="photoActionSheet" type="bottom">
        <view class="action-sheet">
          <view class="action-sheet-title">选择照片</view>
          <view class="action-item" @click="takePhoto">
            <uni-icons type="camera-filled" size="24" color="#3c9cff"></uni-icons>
            <text>拍照</text>
          </view>
          <view class="action-item" @click="chooseFromAlbum">
            <uni-icons type="image-filled" size="24" color="#3c9cff"></uni-icons>
            <text>从相册选择</text>
          </view>
          <view class="action-item cancel" @click="closeActionSheet">
            <text>取消</text>
          </view>
        </view>
      </uni-popup>
      
      <!-- 房间选择弹窗 -->
      <uni-popup ref="roomSelector" type="bottom" :mask-click="false" :safe-area="false">
        <view class="room-selector">
          <view class="room-selector-header">
            <text class="room-selector-title">选择房间</text>
            <text class="room-selector-close" @click="closeRoomSelector">取消</text>
          </view>
          <scroll-view 
            scroll-y="true" 
            class="room-list" 
            :style="{height: '70vh'}"
            @scrolltolower="loadMoreRooms"
            :lower-threshold="50"
          >
            <view v-if="roomList.length === 0 && !roomListLoading" class="empty-room">
              <uni-icons type="home" size="48" color="#ccc"></uni-icons>
              <text class="empty-text">暂无空闲房间</text>
            </view>
            <view v-for="room in roomList" :key="room.roomId" class="room-item" @click="selectRoom(room)">
              <view class="room-info">
                <text class="room-number">{{ room.name }}</text>
                <text class="room-type">{{ room.buildingName }}</text>
              </view>
              <!-- <view class="room-details">
                <text class="room-price">￥{{ room.price }}/月</text>
                <text class="room-area">{{ room.area }}㎡</text>
              </view> -->
              <uni-icons v-if="formData.roomId === room.roomId" type="checkmarkempty" size="20" color="#3c9cff"></uni-icons>
            </view>
            
            <!-- 加载更多提示 -->
            <view v-if="roomListLoading" class="loading-more">
              <uni-icons type="reload" size="20" color="#999"></uni-icons>
              <text class="loading-text">加载中...</text>
            </view>
            
            <!-- 没有更多数据提示 -->
            <view v-if="!hasMoreRooms && roomList.length > 0" class="no-more">
              <text class="no-more-text">没有更多房间了</text>
            </view>
          </scroll-view>
        </view>
      </uni-popup>
      

      
      <!-- 使用新的Canvas 2D接口 -->
      <canvas type="2d" id="compressCanvas" style="width: 800px; height: 800px; position: absolute; left: -9999px; top: -9999px; z-index: -1;"></canvas>
    </view>
  </template>
  
  <script>
  import { idCardPattern, phonePattern } from '@/utils/common'
  import { faceVerify, getInfo } from '@/api/login'
  import config from '@/config'
  import { getToken } from '@/utils/auth'
  import { submitPreCheckIn, getLatestPreCheckIn } from '@/api/preCheckIn'
  import { emptyRoomList } from '@/api/room/index'
  import store from '@/store'
  export default {
    data() {
      return {
        formData: {
          name: '',
          idCardNumber: '',
          renterType: '',
          picUrl: '',
          contacts: '',
          roomId: '',
          mainFlag: '1'
        },
        apartmentId: '',
        coTenants: [],
        roomList: [],
        selectedRoom: null,
        // 房间列表分页相关
        roomListParams: {
          pageNum: 1,
          pageSize: 20
        },
        roomListLoading: false,
        hasMoreRooms: true,
        rules: {
          name: {
            rules: [
              { required: true, errorMessage: '请输入姓名' }
            ]
          },
          idCardNumber: {
            rules: [
              { required: true, errorMessage: '请输入身份证号' },
              { pattern: idCardPattern(), errorMessage: '请输入正确的身份证号' }
            ]
          },
          renterType: {
            rules: [
              { required: true, errorMessage: '请选择房客类型' }
            ]
          },
          picUrl: {
            rules: [
              { required: true, errorMessage: '请上传人脸照片' }
            ]
          },
          contacts: {
            rules: [
              { required: true, errorMessage: '请输入联系方式' },
              { pattern: phonePattern(), errorMessage: '请输入正确的联系方式' }
            ]
          }
        },
        // 图片压缩相关参数
        imageCompressOptions: {
          maxSize: 1024 * 1024, // 1MB
          quality: 0.8 // 初始压缩质量
        },
        // Canvas 2D 上下文
        canvasContext: null,
        currentPhotoTarget: null, // 添加当前操作的照片目标
        // 房客类型选项
        renterTypeOptions: [
          { value: '1', text: '省内' },
          { value: '2', text: '省外' }
        ]
      }
    },
    onReady() {
      // 在页面准备好后获取Canvas 2D上下文
      this.initCanvas();
    },
    onLoad(options) {
      if (options.q) {
        const queryString = decodeURIComponent(options.q).split("?")[1]
        this.apartmentId = queryString.split("=")[1];
        // 缓存扫码携带的公寓ID，防止登录后页面刷新导致参数丢失
        store.dispatch('SetPreCheckInApartmentId', this.apartmentId);
        this.getLatestPreCheckInInfo();
      } else {
        let apartmentId = store.state.user.preCheckInApartmentId;
        if (apartmentId) {
          this.apartmentId = apartmentId;
          this.getLatestPreCheckInInfo();
        } else {
          // 提示重新扫码
          uni.showToast({
            title: '扫码参数丢失，请重新扫码',
            icon: 'none'
          });
        }
      }
      // 获取用户信息并回显
      this.getUserInfo();
    },
    methods: {
      // 初始化Canvas 2D上下文
      initCanvas() {
        const query = uni.createSelectorQuery().in(this);
        query.select('#compressCanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            if (res[0]) {
              const canvas = res[0].node;
              this.canvasContext = canvas.getContext('2d');
              
              // 设置canvas大小
              canvas.width = 800;
              canvas.height = 800;
            }
          });
      },

      // 获取最新的预登记信息
      getLatestPreCheckInInfo() {
        getLatestPreCheckIn().then(res => {
          console.log(res);
          // 检查状态是否为已入住
          if (res.data && res.data.apartmentId) {
            // 弹窗提示用户已经登记过
            uni.showModal({
              title: '提示',
              content: '您已经在其他地方登记过了，是否重新登记？',
              confirmText: '重新登记',
              cancelText: '返回首页',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  // 用户选择重新登记，关闭弹窗，继续当前流程
                  console.log('用户选择重新登记');
                } else if (modalRes.cancel) {
                  // 用户选择返回首页 
                  this.$tab.reLaunch('/pages/index');
                }
              }
            });
          }
        }).catch(err => {
          console.error('获取最新预登记信息失败:', err);
        });
      },
  
      
      // 打开底部操作表
      openPhotoActionSheet(target) {
        this.currentPhotoTarget = target; // target可能是'main'或者同住人的索引
        this.$refs.photoActionSheet.open();
      },
      
      // 关闭底部操作表
      closeActionSheet() {
        this.$refs.photoActionSheet.close();
      },
      
      // 拍照
      takePhoto() {
        uni.chooseImage({
          count: 1,
          sourceType: ['camera'],
          success: (res) => {
            this.handleImageSuccess(res);
          },
          fail: (err) => {
            uni.showToast({
              title: '拍照失败',
              icon: 'none'
            });
          },
          complete: () => {
            this.closeActionSheet();
          }
        });
      },
      
      // 从相册选择
      chooseFromAlbum() {
        uni.chooseImage({
          count: 1,
          sourceType: ['album'],
          success: (res) => {
            this.handleImageSuccess(res);
          },
          fail: (err) => {
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          },
          complete: () => {
            this.closeActionSheet();
          }
        });
      },
      
      // 处理图片选择成功
      handleImageSuccess(res) {
        const tempFilePath = res.tempFilePaths[0];
        
        // 获取图片信息，检查大小
        uni.getFileInfo({
          filePath: tempFilePath,
          success: (fileInfo) => {
            console.log('原始图片大小：', fileInfo.size / 1024, 'KB');
            
            // 如果图片大于1MB，进行压缩
            if (fileInfo.size > this.imageCompressOptions.maxSize) {
              uni.showLoading({
                title: '图片压缩中...'
              });
              this.compressImage(tempFilePath, fileInfo.size);
            } else {
              // 图片小于1MB，直接使用
              this.setPhotoUrl(tempFilePath);
            }
          },
          fail: (err) => {
            console.error('获取图片信息失败', err);
            uni.showToast({
              title: '获取图片信息失败',
              icon: 'none'
            });
          }
        });
      },
      
      // 设置照片URL
      setPhotoUrl(url) {
        if (this.currentPhotoTarget === 'main') {
          this.formData.picUrl = url;
        } else if (typeof this.currentPhotoTarget === 'number') {
          this.coTenants[this.currentPhotoTarget].picUrl = url;
        }
      },
      
      // 压缩图片
      compressImage(filePath, originalSize) {
        let quality = this.imageCompressOptions.quality;
        
        // 根据原始大小调整压缩质量
        if (originalSize > 5 * 1024 * 1024) { // 大于5MB
          quality = 0.6;
        } else if (originalSize > 3 * 1024 * 1024) { // 大于3MB
          quality = 0.7;
        }
        
        // 使用uni.compressImage进行压缩
        uni.compressImage({
          src: filePath,
          quality: quality * 100,
          success: (res) => {
            // 获取压缩后的图片信息
            uni.getFileInfo({
              filePath: res.tempFilePath,
              success: (fileInfo) => {
                console.log('压缩后图片大小：', fileInfo.size / 1024, 'KB');
                
                if (fileInfo.size > this.imageCompressOptions.maxSize) {
                  this.compressImageByCanvas(res.tempFilePath);
                } else {
                  this.setPhotoUrl(res.tempFilePath);
                  uni.hideLoading();
                }
              },
              fail: (err) => {
                console.error('获取压缩后图片信息失败', err);
                uni.hideLoading();
                uni.showToast({
                  title: '图片处理失败',
                  icon: 'none'
                });
              }
            });
          },
          fail: (err) => {
            console.error('压缩图片失败', err);
            this.compressImageByCanvas(filePath);
          }
        });
      },
      
      // 使用Canvas 2D压缩图片
      compressImageByCanvas(filePath) {
        if (!this.canvasContext) {
          console.error('Canvas 2D上下文未初始化');
          uni.hideLoading();
          uni.showToast({
            title: '图片处理失败',
            icon: 'none'
          });
          return;
        }
        
        // 获取图片信息
        uni.getImageInfo({
          src: filePath,
          success: (imageInfo) => {
            // 计算新的尺寸，保持宽高比
            const maxWidth = 800;
            const maxHeight = 800;
            
            let newWidth = imageInfo.width;
            let newHeight = imageInfo.height;
            
            if (newWidth > maxWidth || newHeight > maxHeight) {
              if (newWidth / newHeight > 1) {
                // 宽图
                newWidth = maxWidth;
                newHeight = Math.floor(imageInfo.height * (maxWidth / imageInfo.width));
              } else {
                // 高图
                newHeight = maxHeight;
                newWidth = Math.floor(imageInfo.width * (maxHeight / imageInfo.height));
              }
            }
            
            // 创建图片对象
            const query = uni.createSelectorQuery().in(this);
            query.select('#compressCanvas')
              .fields({ node: true, size: true })
              .exec((res) => {
                if (res[0]) {
                  const canvas = res[0].node;
                  const ctx = this.canvasContext;
                  
                  // 清空画布
                  ctx.clearRect(0, 0, canvas.width, canvas.height);
                  
                  // 创建图片对象
                  const img = canvas.createImage();
                  img.onload = () => {
                    // 绘制图片到画布
                    ctx.drawImage(img, 0, 0, newWidth, newHeight);
                    
                    // 导出图片
                    uni.canvasToTempFilePath({
                      canvas: canvas,
                      width: newWidth,
                      height: newHeight,
                      destWidth: newWidth,
                      destHeight: newHeight,
                      fileType: 'jpg',
                      quality: 0.8,
                      success: (res) => {
                        // 检查压缩后的大小
                        uni.getFileInfo({
                          filePath: res.tempFilePath,
                          success: (fileInfo) => {
                            console.log('Canvas压缩后图片大小：', fileInfo.size / 1024, 'KB');
                            
                            if (fileInfo.size > this.imageCompressOptions.maxSize && newWidth > 400) {
                              // 如果还是太大，继续降低尺寸
                              this.compressImageByCanvas(res.tempFilePath);
                            } else {
                              this.setPhotoUrl(res.tempFilePath);
                              uni.hideLoading();
                            }
                          },
                          fail: (err) => {
                            console.error('获取Canvas压缩后图片信息失败', err);
                            uni.hideLoading();
                            uni.showToast({
                              title: '图片处理失败',
                              icon: 'none'
                            });
                          }
                        });
                      },
                      fail: (err) => {
                        console.error('Canvas导出图片失败', err);
                        uni.hideLoading();
                        uni.showToast({
                          title: '图片处理失败',
                          icon: 'none'
                        });
                      }
                    }, this);
                  };
                  
                  img.onerror = () => {
                    console.error('图片加载失败');
                    uni.hideLoading();
                    uni.showToast({
                      title: '图片处理失败',
                      icon: 'none'
                    });
                  };
                  
                  // 设置图片源
                  img.src = filePath;
                } else {
                  console.error('未找到Canvas节点');
                  uni.hideLoading();
                  uni.showToast({
                    title: '图片处理失败',
                    icon: 'none'
                  });
                }
              });
          },
          fail: (err) => {
            console.error('获取图片信息失败', err);
            uni.hideLoading();
            uni.showToast({
              title: '图片处理失败',
              icon: 'none'
            });
          }
        });
      },

      // 修改uploadImage函数为通用的上传函数
      async uploadImage(filePath, type, index) {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: `${config.baseUrl}/file/upload`,
            filePath: filePath,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + getToken()
            },
            success: (uploadRes) => {
              try {
                const data = JSON.parse(uploadRes.data);
                if (data.code === 200 && data.data && data.data.url) {
                  // 根据类型更新不同对象的图片URL
                  if (type === 'main') {
                    this.formData.picUrl = data.data.url;
                  } else if (type === 'coTenant' && typeof index === 'number') {
                    this.coTenants[index].picUrl = data.data.url;
                  }
                  resolve(data.data.url);
                } else {
                  reject(new Error(data.message || '图片上传失败'));
                }
              } catch (e) {
                reject(new Error('图片上传失败，返回数据格式错误'));
              }
            },
            fail: (err) => {
              reject(new Error('图片上传失败'));
            }
          });
        });
      },
      
      // 判断是否需要上传图片
      needUpload(url) {
        if (!url) return false;
        // 判断是否为临时文件路径（微信小程序、APP等平台的临时文件路径特征）
        return url.startsWith('wxfile://') || 
               url.startsWith('http://tmp/') || 
               url.startsWith('file://') ||
               /^[\w\-]+:\/\/tmp/.test(url);
      },
      
      // 修改主租户图片上传方法
      async uploadMainTenantImage() {
        if (!this.formData.picUrl) {
          throw new Error('主要登记人照片不能为空');
        }
        
        // 使用新的判断方法
        if (this.needUpload(this.formData.picUrl)) {
          try {
            await this.uploadImage(this.formData.picUrl, 'main');
          } catch (error) {
            console.error('主要登记人照片上传失败:', error);
            throw error;
          }
        }
      },

      // 修改同住人图片上传方法
      async uploadCoTenantImage(index) {
        const tenant = this.coTenants[index];
        if (!tenant.picUrl) {
          throw new Error(`同住人${index + 1}照片不能为空`);
        }
        
        // 使用新的判断方法
        if (this.needUpload(tenant.picUrl)) {
          try {
            await this.uploadImage(tenant.picUrl, 'coTenant', index);
          } catch (error) {
            console.error(`同住人${index + 1}照片上传失败:`, error);
            throw error;
          }
        }
      },
      
      // 获取用户信息
      getUserInfo() {
        getInfo().then(res => {
          const { phonenumber, idCardNumber, renterName, picUrl } = res.data;
          if (phonenumber || idCardNumber || renterName || picUrl) {
            this.formData.name = renterName || '';
            this.formData.idCardNumber = idCardNumber || '';
            this.formData.picUrl = picUrl || '';
            this.formData.contacts = phonenumber || '';
          }
        });
      },

      // 获取空闲房间列表
      getRoomList(isLoadMore = false) {
        if (this.roomListLoading) return;
        
        this.roomListLoading = true;
        
        const data = {
          apartmentId: this.apartmentId,
          pageNum: this.roomListParams.pageNum,
          pageSize: this.roomListParams.pageSize
        };
        
        emptyRoomList(data).then(res => {
          const newRooms = res.rows || [];
          
          if (isLoadMore) {
            // 加载更多，追加到现有列表
            this.roomList = [...this.roomList, ...newRooms];
          } else {
            // 首次加载，替换列表
            this.roomList = newRooms;
          }
          
          // 判断是否还有更多数据
          this.hasMoreRooms = newRooms.length >= this.roomListParams.pageSize;
          
        }).catch(err => {
          console.error('获取房间列表失败:', err);
          uni.showToast({
            title: '获取房间列表失败',
            icon: 'none'
          });
        }).finally(() => {
          this.roomListLoading = false;
        });
      },

      // 打开房间选择器
      openRoomSelector() {
        // 重置分页参数
        this.roomListParams.pageNum = 1;
        this.hasMoreRooms = true;
        
        if (this.roomList.length === 0) {
          this.getRoomList();
        }
        this.$refs.roomSelector.open();
      },

      // 关闭房间选择器
      closeRoomSelector() {
        this.$refs.roomSelector.close();
      },

      // 选择房间
      selectRoom(room) {
        this.formData.roomId = room.roomId;
        this.selectedRoom = room;
        this.closeRoomSelector();
      },

      // 加载更多房间
      loadMoreRooms() {
        if (!this.hasMoreRooms || this.roomListLoading) {
          return;
        }
        
        this.roomListParams.pageNum += 1;
        this.getRoomList(true);
      },

      // 添加同住人
      addCoTenant() {
        this.coTenants.push({
          name: '',
          idCardNumber: '',
          renterType: '',
          picUrl: '',
          contacts: '',
          mainFlag: '2'
        });
      },

      // 删除同住人
      removeCoTenant(index) {
        this.coTenants.splice(index, 1);
      },

      // 修改提交表单方法
      submitForm() {
        this.$refs.form.validate().then(res => {
          // 验证同住人表单
          let isValid = true;
          this.coTenants.forEach((tenant, index) => {
            if (!tenant.name || !tenant.idCardNumber || !tenant.renterType || !tenant.contacts || !tenant.picUrl) {
              isValid = false;
              uni.showToast({
                title: `请完善第${index + 1}位同住人信息`,
                icon: 'none'
              });
            }
          });

          if (!isValid) return;

          uni.showLoading({
            title: '提交中...'
          });

          // 处理图片上传
          this.uploadImages();
        }).catch(err => {
          console.log('表单错误：', err);
          if (err && err.length > 0) {
            uni.showToast({
              title: err[0].errorMessage || '表单填写有误，请检查',
              icon: 'none',
              duration: 2000
            });
          }
        });
      },

      // 修改上传所有图片的方法
      async uploadImages() {
        try {
          uni.showLoading({
            title: '正在上传图片...',
            mask: true
          });

          // 上传主租户图片
          await this.uploadMainTenantImage();

          // 上传所有同住人图片
          for (let i = 0; i < this.coTenants.length; i++) {
            await this.uploadCoTenantImage(i);
          }

          // 所有图片上传完成后提交表单
          this.submitFaceVerify();
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: error.message || '图片上传失败',
            icon: 'none'
          });
        }
      },

      // 修改提交人脸验证方法
      submitFaceVerify() {
        // 构建提交数据，将roomId提取到外层
        const mainTenantData = { ...this.formData };
        delete mainTenantData.roomId; // 从租户信息中移除roomId
        
        const renterList = [
          mainTenantData,
          ...this.coTenants
        ];

        const submitData = {
          apartmentId: this.apartmentId,
          roomId: this.formData.roomId || '', // 将roomId提取到外层
          renterList: renterList
        };

        submitPreCheckIn(submitData).then(res => {
          store.dispatch('SetPreCheckInApartmentId', '');
          uni.showToast({
            title: '登记成功',
            icon: 'success'
          });
          this.$tab.reLaunch('/pages/index')
        }).catch(err => {
          uni.showToast({
            title: '提交失败',
            icon: 'none'
          });
          console.error('登记失败:', err);
        }).finally(() => {
          uni.hideLoading();
        });
      },
      
    }
  }
  </script>
  
  <style lang="scss">
  .face-verify-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding: 30rpx;
    box-sizing: border-box;
    
    .page-header {
      text-align: center;
      padding: 40rpx 0;
      
      .page-title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 16rpx;
      }
      
      .page-desc {
        font-size: 26rpx;
        color: #666;
      }
    }
    
    .form-card {
      background-color: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      margin-bottom: 40rpx;
      
      .form-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        .form-title {
          font-size: 30rpx;
          font-weight: 600;
          color: #333;
        }

        .delete-btn {
          font-size: 26rpx;
          color: #ff4d4f;
          padding: 10rpx;
        }
      }
      
      :deep(.uni-forms-item) {
        padding-bottom: 30rpx;
        margin-bottom: 10rpx;
        
        .uni-forms-item__label {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 12rpx;
        }
        
        .uni-easyinput__content {
          height: 88rpx;
          background-color: #f8f9fc;
          border-radius: 8rpx;
          border: 1px solid #e5e7eb;
          
          &.is-input-border {
            border: 1px solid #e5e7eb;
            
            &:hover, &:focus {
              border-color: #3c9cff;
            }
          }
        }
      }
      
      .room-select-wrapper {
        .room-select-container {
          height: 68rpx;
          border-radius: 8rpx;
          border: 1px solid #e5e7eb;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 24rpx;
          
          &:active {
            background-color: #eef1f6;
          }
          
          .selected-room {
            font-size: 28rpx;
            color: #333;
          }
          
          .room-placeholder {
            font-size: 28rpx;
            color: #999;
          }
        }
      }



      .face-photo-wrapper {
        .face-photo-container {
          width: 240rpx;
          height: 240rpx;
          border: 1px dashed #d0d7de;
          border-radius: 12rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          overflow: hidden;
          background-color: #f8f9fc;
          transition: all 0.3s;
          
          &:active {
            background-color: #eef1f6;
          }
          
          .face-photo {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .face-photo-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #999;
            
            .placeholder-text {
              font-size: 26rpx;
              margin-top: 16rpx;
              color: #666;
            }
          }
        }
        
        .photo-tip {
          font-size: 24rpx;
          color: #999;
          margin-top: 16rpx;
          display: block;
        }
      }
    }
    
    .submit-btn-container {
      padding: 0 20rpx;
      
      .submit-btn {
        width: 100%;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 32rpx;
        font-weight: 500;
        border-radius: 45rpx;
        background: linear-gradient(to right, #3c9cff, #5dabff);
        box-shadow: 0 10rpx 20rpx rgba(60, 156, 255, 0.3);
        border: none;
      }
    }
    
    .add-tenant-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 88rpx;
      background-color: #fff;
      border-radius: 8rpx;
      margin: 20rpx 0;
      color: #3c9cff;
      font-size: 28rpx;

      uni-icons {
        margin-right: 10rpx;
      }

      &:active {
        background-color: #f8f8f8;
      }
    }
  }
  
  .action-sheet {
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;
    padding-bottom: env(safe-area-inset-bottom);
    
    .action-sheet-title {
      text-align: center;
      font-size: 28rpx;
      color: #999;
      padding: 20rpx 0;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .action-item {
      height: 110rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
      border-bottom: 1px solid #f0f0f0;
      
      uni-icons {
        margin-right: 10rpx;
      }
      
      &:active {
        background-color: #f8f8f8;
      }
      
      &.cancel {
        margin-top: 20rpx;
        color: #666;
        border-bottom: none;
      }
    }
  }

  .room-selector {
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;
    height: 80vh;
    display: flex;
    flex-direction: column;
    
    .room-selector-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1px solid #f0f0f0;
      flex-shrink: 0;
      
      .room-selector-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .room-selector-close {
        font-size: 28rpx;
        color: #666;
        padding: 10rpx;
      }
    }
    
    .room-list {
      flex: 1;
      
      .empty-room {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 80rpx 0;
        
        .empty-text {
          font-size: 28rpx;
          color: #999;
          margin-top: 20rpx;
        }
      }
      
      .room-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 30rpx;
        border-bottom: 1px solid #f0f0f0;
        
        &:active {
          background-color: #f8f8f8;
        }
        
        .room-info {
          flex: 1;
          
          .room-number {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            display: block;
            margin-bottom: 8rpx;
          }
          
          .room-type {
            font-size: 26rpx;
            color: #666;
          }
        }
        
        .room-details {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          margin-right: 20rpx;
          
          .room-price {
            font-size: 28rpx;
            font-weight: 600;
            color: #3c9cff;
            margin-bottom: 4rpx;
          }
          
          .room-area {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
      
      .loading-more {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx;
        
        .loading-text {
          font-size: 26rpx;
          color: #999;
          margin-left: 10rpx;
        }
        
        uni-icons {
          animation: rotate 1s linear infinite;
        }
      }
      
      .no-more {
        display: flex;
        justify-content: center;
        padding: 30rpx;
        
        .no-more-text {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  </style>
  